//购物车例子 provider的使用

import 'dart:collection';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'myprovider.dart';

class Item {

  Item(this.price, this.count);

  double price; //单价
  int count; //数量
}


class CartModel extends ChangeNotifier {
  // 用于保存购物车中商品列表
  final List<Item> _items = [];

  // 禁止改变购物车里的商品信息
  UnmodifiableListView<Item> get items => UnmodifiableListView(_items);

  // 购物车中商品的总价
  double get totalPrice =>
      _items.fold(0, (value, item) => value + item.count * item.price);

  // 将 [item] 添加到购物车。这是唯一一种能从外部改变购物车的方法。
  void add(Item item) {
    _items.add(item);
    // 通知监听器（订阅者），重新构建InheritedProvider， 更新状态。
    notifyListeners();
  }
}


class Consumer<T> extends StatelessWidget{

  Consumer({
    Key? key,
    required this.builder,
  }) : super(key: key);

  final Widget Function(BuildContext context, T? value) builder;

  @override
  Widget build(BuildContext context) {

     return  builder(context, ChangeNotifierProvider.of<T>(context),);

  }

}

class ProviderRoute extends StatefulWidget {
  @override
  _ProviderRouteState createState() => _ProviderRouteState();
}

class _ProviderRouteState extends State<ProviderRoute> {

  bool withTree = false; // 复选框选中状态


  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(appBar: AppBar(title:const Text("测试provider")),
      body: Center(
        child: ChangeNotifierProvider<CartModel>(
          data: CartModel(),
          child: Builder(builder: (context) {
            return Column(
              children: <Widget>[
                Builder(builder: (context) {
                  // var cart = ChangeNotifierProvider.of<CartModel>(context);
                  // return Text("总价: ${cart!.totalPrice}");
                   return Consumer<CartModel>(builder: (context,cart) => Text("总价: ${cart!.totalPrice}"),);

                }),
                Builder(builder: (context) {
                  print("ElevatedButton build"); //在后面优化部分会用到
                  return ElevatedButton(
                    child: const Text("添加商品"),
                    onPressed: () async  {

                      //给购物车中添加商品，添加后总价会更新
                      // ChangeNotifierProvider.of<CartModel>(context)!.add(Item(20.0, 1));
                      _testDialog(context,withTree);
                    },
                  );
                }),
              ],
            );
          }),
        ),
      ),
    ),
    );
  }

   void  _testDialog(BuildContext context,bool withTree) async{
     bool? _withTree = true; //记录复选框是否选中
     var tipsDialog =  AlertDialog(title:const Text("警告"),content:  DialogCheckbox(
       value: _withTree, onChanged: (bool? value){
         _withTree = value;
       },
     )
       ,actions: <Widget>[
       TextButton(onPressed: (){


         print("确定");
         Navigator.of(context).pop(true);

       }, child: const Text("确定")),
       TextButton(onPressed: (){
         print("取消");
         Navigator.of(context).pop(true);

       }, child: const Text("取消"))
     ],);
        bool  result =  await showDialog(context: context, builder: (context)=>tipsDialog);
   }
}


 class  DialogCheckbox extends StatefulWidget{

     DialogCheckbox({Key? key,this.value,required this.onChanged,});

     bool? value;
     final ValueChanged<bool?> onChanged;
    @override
     State<StatefulWidget> createState() => _DialogCheckboxState();
 }


 class  _DialogCheckboxState  extends  State<DialogCheckbox>{

     bool? value;

       @override
    void initState() {
      value = widget.value;
      super.initState();
       }
     @override
      Widget build(BuildContext context) {

          return Checkbox(value: value, onChanged: (bool? v){
             widget.onChanged(v);
            setState(() {
              value =v;
            });

          },);
      }
 }



